package com.example.vaultmysql.controller;

import com.example.vaultmysql.service.DataInitializationService;
import com.example.vaultmysql.service.DatabaseConfigService;
import com.example.vaultmysql.service.VaultService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 主页控制器
 * 提供系统首页和基本信息
 * 
 * @author System
 * @version 1.0.0
 */
@Slf4j
@Controller
public class HomeController {

    @Autowired
    private DataInitializationService dataInitializationService;

    @Autowired
    private DatabaseConfigService databaseConfigService;

    @Autowired
    private VaultService vaultService;

    /**
     * 系统首页
     */
    @GetMapping("/")
    public String home(Model model) {
        try {
            // 获取系统初始化状态
            DataInitializationService.InitializationStatus initStatus = 
                dataInitializationService.getInitializationStatus();
            
            // 获取数据库配置统计
            DatabaseConfigService.DatabaseConfigStats dbStats = 
                databaseConfigService.getStats();
            
            model.addAttribute("initStatus", initStatus);
            model.addAttribute("dbStats", dbStats);
            model.addAttribute("currentTime", LocalDateTime.now());
            
            return "index";
        } catch (Exception e) {
            log.error("加载首页失败", e);
            model.addAttribute("error", "系统加载失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 系统状态API
     */
    @GetMapping("/api/system/status")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getSystemStatus() {
        try {
            // 获取系统初始化状态
            DataInitializationService.InitializationStatus initStatus = 
                dataInitializationService.getInitializationStatus();
            
            // 获取数据库配置统计
            DatabaseConfigService.DatabaseConfigStats dbStats = 
                databaseConfigService.getStats();
            
            // 测试Vault连接
            boolean vaultConnected = false;
            try {
                vaultService.testConnection();
                vaultConnected = true;
            } catch (Exception e) {
                log.warn("Vault连接测试失败: {}", e.getMessage());
            }
            
            return ResponseEntity.ok(Map.of(
                "status", "running",
                "timestamp", System.currentTimeMillis(),
                "initialization", Map.of(
                    "initialized", initStatus.isInitialized(),
                    "vaultConfigs", initStatus.getVaultConfigCount(),
                    "databaseConfigs", initStatus.getDatabaseConfigCount(),
                    "enabledDatabases", initStatus.getEnabledDatabaseCount()
                ),
                "database", Map.of(
                    "totalConfigs", dbStats.getTotalCount(),
                    "enabledConfigs", dbStats.getEnabledCount(),
                    "disabledConfigs", dbStats.getDisabledCount(),
                    "enabledPercentage", dbStats.getEnabledPercentage()
                ),
                "vault", Map.of(
                    "connected", vaultConnected,
                    "url", "http://localhost:8200"
                ),
                "version", "1.0.0",
                "environment", "development"
            ));
        } catch (Exception e) {
            log.error("获取系统状态失败", e);
            return ResponseEntity.ok(Map.of(
                "status", "error",
                "message", e.getMessage(),
                "timestamp", System.currentTimeMillis()
            ));
        }
    }

    /**
     * 系统信息API
     */
    @GetMapping("/api/system/info")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getSystemInfo() {
        try {
            Runtime runtime = Runtime.getRuntime();
            long maxMemory = runtime.maxMemory();
            long totalMemory = runtime.totalMemory();
            long freeMemory = runtime.freeMemory();
            long usedMemory = totalMemory - freeMemory;
            
            return ResponseEntity.ok(Map.of(
                "application", Map.of(
                    "name", "Vault MySQL高并发服务",
                    "version", "1.0.0",
                    "description", "基于HashiCorp Vault的MySQL数据库凭证管理和高并发测试系统"
                ),
                "system", Map.of(
                    "javaVersion", System.getProperty("java.version"),
                    "osName", System.getProperty("os.name"),
                    "osVersion", System.getProperty("os.version"),
                    "osArch", System.getProperty("os.arch")
                ),
                "memory", Map.of(
                    "maxMemory", formatBytes(maxMemory),
                    "totalMemory", formatBytes(totalMemory),
                    "usedMemory", formatBytes(usedMemory),
                    "freeMemory", formatBytes(freeMemory),
                    "usagePercentage", Math.round((double) usedMemory / totalMemory * 100)
                ),
                "features", Map.of(
                    "vaultIntegration", true,
                    "mysqlConnectionPool", true,
                    "concurrencyTesting", true,
                    "webInterface", true,
                    "restApi", true,
                    "monitoring", true
                ),
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("获取系统信息失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "error", e.getMessage()
            ));
        }
    }

    /**
     * 健康检查API
     */
    @GetMapping("/api/health")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> healthCheck() {
        try {
            boolean healthy = true;
            StringBuilder issues = new StringBuilder();
            
            // 检查数据库配置
            try {
                databaseConfigService.getStats();
            } catch (Exception e) {
                healthy = false;
                issues.append("数据库配置服务异常; ");
            }
            
            // 检查Vault连接
            try {
                vaultService.testConnection();
            } catch (Exception e) {
                // Vault连接失败不影响整体健康状态，只是功能受限
                issues.append("Vault连接异常; ");
            }
            
            return ResponseEntity.ok(Map.of(
                "status", healthy ? "UP" : "DOWN",
                "timestamp", System.currentTimeMillis(),
                "issues", issues.toString(),
                "checks", Map.of(
                    "database", "UP",
                    "vault", "UNKNOWN",
                    "memory", "UP"
                )
            ));
        } catch (Exception e) {
            log.error("健康检查失败", e);
            return ResponseEntity.ok(Map.of(
                "status", "DOWN",
                "timestamp", System.currentTimeMillis(),
                "error", e.getMessage()
            ));
        }
    }

    /**
     * 重新初始化系统数据
     */
    @PostMapping("/api/system/reinitialize")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> reinitializeSystem() {
        try {
            dataInitializationService.resetAllData();
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "系统数据重新初始化成功",
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("重新初始化系统失败", e);
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "重新初始化失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 格式化字节数
     */
    private String formatBytes(long bytes) {
        if (bytes < 1024) return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(1024));
        String pre = "KMGTPE".charAt(exp - 1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(1024, exp), pre);
    }

    /**
     * 错误页面
     */
    @GetMapping("/error")
    public String error() {
        return "error";
    }

    /**
     * 关于页面
     */
    @GetMapping("/about")
    public String about(Model model) {
        model.addAttribute("version", "1.0.0");
        model.addAttribute("buildTime", LocalDateTime.now());
        return "about";
    }
}